<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="150px">
      <el-form-item label="请输入老人姓名" prop="oldName">
        <el-input
          v-model="queryParams.oldName"
          placeholder="请输入老人姓名"
          clearable
          @keyup.enter="handleQuery" />
      </el-form-item>

      <el-form-item label="请输入护理员姓名" prop="nurseName">
        <el-input
          v-model="queryParams.nurseName"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery" />
      </el-form-item>

      <el-form-item label="护理项目" prop="nursingProject">
        <el-input
          v-model="queryParams.nursingProject"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery" />
      </el-form-item>

      <el-form-item label="预计服务时间" prop="expectedTime">
        <el-date-picker
          clearable
          v-model="queryParams.expectedTime"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          format="YYYY-MM-DD HH:mm:ss"
          placeholder="请选择预计服务时间">
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button @click="resetQuery">重置</el-button>
        <el-button type="primary" @click="handleQuery">搜索</el-button>
      </el-form-item>
    </el-form>

    <!-- 状态切换栏 -->
    <div class="status-tabs" style="margin-bottom: 20px">
      <el-button
        :type="queryParams.status === 1 ? 'primary' : ''"
        @click="handleStatusChange(1)"
        style="margin-right: 10px">
        待执行
      </el-button>
      <el-button
        :type="queryParams.status === 2 ? 'primary' : ''"
        @click="handleStatusChange(2)"
        style="margin-right: 10px">
        已执行
      </el-button>
      <el-button
        :type="queryParams.status === 3 ? 'primary' : ''"
        @click="handleStatusChange(3)">
        已取消
      </el-button>
    </div>

    <!-- 列表显示区域 -->
    <el-table v-loading="loading" :data="taskList">
      <el-table-column type="index" label="序号" width="45" align="center" />
      <el-table-column label="老人姓名" align="center" prop="oldName" />
      <el-table-column label="床位号" align="center" prop="bedNo" />
      <el-table-column label="护理项目名称" align="center" prop="projectName" />
      <el-table-column label="项目类型" align="center" prop="taskType">
        <template #default="scope">
          <dict-tag :options="sys_task_type" :value="scope.row.taskType" />
        </template>
      </el-table-column>
      <el-table-column
        label="护理员姓名"
        align="center"
        width="120"
        prop="nurseNameList">
        <template #default="scope">
          <span>{{ formatNurseNameList(scope.row.nurseNameList) }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="期望服务时间"
        align="center"
        prop="expectedTime"
        width="180">
        <template #default="scope">
          <span>{{
            parseTime(scope.row.expectedTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="creator" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createdTime"
        width="180">
        <template #default="scope">
          <span>{{
            parseTime(scope.row.createdAt, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="关联单据" align="center" prop="relatedDocNo" />

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width">
        <template #default="scope">
          <!-- v-hasPermi="['service:task:cancel']" -->
          <el-button
            v-if="scope.row.status == 1"
            link
            type="danger"
            @click="handleCancel(scope.row)">
            取消
          </el-button>

          <!-- v-hasPermi="['service:task:view']" -->
          <el-button link type="primary" @click="handleView(scope.row)">
            查看
          </el-button>

          <!--  v-hasPermi="['service:task:execute']" -->
          <el-button
            v-if="scope.row.status == 1"
            link
            type="primary"
            @click="handleExecute(scope.row)"
            >执行</el-button
          >

          <!-- v-hasPermi="['service:task:changeTime']" -->
          <el-button
            v-if="scope.row.status == 1"
            link
            type="primary"
            @click="handleChangeTime(scope.row)"
            >改期</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 取消按钮的对话框 -->
    <el-dialog v-model="cancelDialogVisible" width="500">
      <el-form :model="cancelForm">
        <el-form-item label="取消原因">
          <el-input v-model="cancelForm.cancelReason" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleCancelSubmit">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 执行按钮的编辑框 -->
    <el-dialog v-model="executeDialogVisible" width="500">
      <el-form :model="executeForm" ref="executeFormRef" :rules="executeRules">
        <!-- 执行时间 必填项 -->
        <el-form-item label="执行时间" prop="executionTime" required>
          <el-date-picker
            v-model="executeForm.executionTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择执行时间" />
        </el-form-item>
        <!-- 执行图片 必填项 -->
        <el-form-item label="执行图片" prop="executionImages" required>
          <image-upload v-model="executeForm.executionImages" :limit="1" />
        </el-form-item>
        <!-- 执行记录 必填项 -->
        <el-form-item label="执行记录" prop="executionRecord" required>
          <el-input v-model="executeForm.executionRecord" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="executeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleExecuteSubmit">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看任务详情对话框 -->
    <el-dialog v-model="viewDialogVisible" title="任务详情" width="800px">
      <div style="max-height: 600px; overflow-y: auto">
        <!-- 基本信息 -->
        <el-card class="box-card" style="margin-bottom: 20px">
          <template #header>
            <div class="card-header">
              <span style="font-weight: bold; color: #409eff">基本信息</span>
            </div>
          </template>
          <el-row>
            <!-- 左侧：基本信息表单 -->
            <el-col :span="16">
              <el-form :model="viewForm" label-width="100px">
                <!-- 第一行 -->
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="老人姓名">{{
                      viewForm.oldName
                    }}</el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <el-form-item label="护理等级">{{
                      viewForm.levelName
                    }}</el-form-item>
                  </el-col>
                </el-row>
                <!-- 第二行 -->
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="性别">
                      {{
                        viewForm.elderGender == "0"
                          ? "男"
                          : viewForm.elderGender == "1"
                          ? "女"
                          : "未知"
                      }}
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <el-form-item label="年龄"
                      >{{ viewForm.elderAge }}岁</el-form-item
                    >
                  </el-col>
                </el-row>
                <!-- 第三行 -->
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="床位号">{{
                      viewForm.realBedNo
                    }}</el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <el-form-item label="护理员姓名">
                      {{
                        formatNurseNameList(viewForm.nurseNameList)
                      }}</el-form-item
                    >
                  </el-col>
                </el-row>
              </el-form>
            </el-col>

            <!-- 右侧：老人头像图片显示 -->
            <el-col :span="8">
              <div style="padding: 20px; text-align: center">
                <div
                  v-if="viewForm.elderPhoto"
                  style="display: flex; justify-content: center">
                  <el-image
                    :src="viewForm.elderPhoto"
                    style="
                      width: 120px;
                      border-radius: 8px;
                      border: 2px solid #e4e7ed;
                    "
                    fit="cover"
                    :preview-src-list="[viewForm.elderPhoto]"
                    :initial-index="0">
                    <template #error>
                      <div
                        style="
                          display: flex;
                          justify-content: center;
                          align-items: center;
                          width: 100%;
                          height: 100%;
                          background: #f5f7fa;
                          color: #909399;
                          font-size: 14px;
                        ">
                        <i class="el-icon-picture-outline"></i>
                        <span style="margin-left: 5px">暂无图片</span>
                      </div>
                    </template>
                  </el-image>
                </div>
                <div
                  v-else
                  style="
                    width: 120px;
                    height: 120px;
                    margin: 0 auto;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    background: #f5f7fa;
                    color: #909399;
                    font-size: 14px;
                    border-radius: 8px;
                    border: 2px solid #e4e7ed;
                  ">
                  <i class="el-icon-picture-outline"></i>
                  <span style="margin-left: 5px">暂无图片</span>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-card>

        <!-- 护理项目 必显示 -->
        <el-card class="box-card" style="margin-bottom: 20px">
          <template #header>
            <div class="card-header">
              <span style="font-weight: bold; color: #67c23a">护理项目</span>
            </div>
          </template>
          <el-form :model="viewForm" label-width="100px">
            <!-- 第一行 护理项目名字 关联单据 -->
            <el-row>
              <el-col :span="12">
                <el-form-item label="护理项目名称">{{
                  viewForm.projectName
                }}</el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="关联单号">{{
                  viewForm.relatedDocNo
                }}</el-form-item>
              </el-col>
            </el-row>
            <!-- 第二行 执行状态 项目类型 -->
            <el-row>
              <el-col :span="12">
                <el-form-item label="执行状态">
                  <el-tag v-if="viewForm.status == '1'" type="warning"
                    >待执行</el-tag
                  >
                  <el-tag v-else-if="viewForm.status == '2'" type="success"
                    >已执行</el-tag
                  >
                  <el-tag v-else-if="viewForm.status == '3'" type="danger"
                    >已取消</el-tag
                  >
                </el-form-item>
              </el-col>

              <!-- 项目类型 -->
              <el-col :span="12">
                <el-form-item label="项目类型">{{
                  viewForm.taskType == "1" ? "护理等级外" : "护理等级内"
                }}</el-form-item>
              </el-col>
            </el-row>

            <!-- 第三行 创建人 创建时间 -->
            <el-row>
              <el-col :span="12">
                <el-form-item label="创建人">{{
                  viewForm.creator
                }}</el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="创建时间">
                  {{ parseTime(viewForm.createdAt, "{y}-{m}-{d} {h}:{i}:{s}") }}
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 第四行期望时间 备注信息 -->
            <el-row>
              <el-col :span="12">
                <el-form-item label="期望时间">
                  {{
                    parseTime(viewForm.expectedTime, "{y}-{m}-{d} {h}:{i}:{s}")
                  }}
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="备注信息">{{
                  viewForm.remark
                }}</el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>

        <!-- 执行记录 -->
        <el-card class="box-card" v-if="viewForm.status == '2'">
          <template #header>
            <div class="card-header">
              <span style="font-weight: bold; color: #e6a23c">执行记录</span>
            </div>
          </template>
          <el-form :model="viewForm" label-width="100px">
            <!-- 第一行执行人 -->
            <el-row>
              <el-col :span="24">
                <el-form-item label="执行人">{{
                  viewForm.updater
                }}</el-form-item>
              </el-col>
            </el-row>
            <!-- 第二行执行时间 -->
            <el-row>
              <el-col :span="24">
                <el-form-item label="执行时间">
                  {{ parseTime(viewForm.updatedAt, "{y}-{m}-{d} {h}:{i}:{s}") }}
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 第三行执行图片 -->
            <el-row
              v-if="
                viewForm.parsedExecutionImages &&
                viewForm.parsedExecutionImages.length > 0
              ">
              <el-col :span="24">
                <el-form-item label="执行图片">
                  <div style="display: flex; flex-wrap: wrap; gap: 10px">
                    <el-image
                      v-for="(image, index) in viewForm.parsedExecutionImages"
                      :key="index"
                      :src="image"
                      style="width: 100px; height: 100px; border-radius: 4px"
                      fit="cover"
                      :preview-src-list="viewForm.parsedExecutionImages"
                      :initial-index="index" />
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 第四行执行记录 -->
            <el-row>
              <el-col :span="24">
                <el-form-item label="执行记录">{{
                  viewForm.executionRecord
                }}</el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>

        <!-- 取消记录 -->
        <el-card class="box-card" v-if="viewForm.status == '3'">
          <template #header>
            <div class="card-header">
              <span style="font-weight: bold; color: #e6a23c">取消记录</span>
            </div>
          </template>
          <el-form :model="viewForm" label-width="100px">
            <!-- 第一行取消人 -->
            <el-row>
              <el-col :span="24">
                <el-form-item label="执行人">{{
                  viewForm.updater
                }}</el-form-item>
              </el-col>
            </el-row>
            <!-- 第二行取消时间 -->
            <el-row>
              <el-col :span="24">
                <el-form-item label="取消时间">
                  {{ parseTime(viewForm.updatedAt, "{y}-{m}-{d} {h}:{i}:{s}") }}
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 第三行取消原因 -->
            <el-row>
              <el-col :span="24">
                <el-form-item label="取消原因">{{
                  viewForm.cancelReason
                }}</el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </div>

      <template #footer>
        <div class="dialog-footer" style="text-align: center">
          <el-button type="primary" @click="viewDialogVisible = false"
            >返回</el-button
          >
        </div>
      </template>
    </el-dialog>

    <!-- 改期任务对话框 -->
    <el-dialog v-model="changeTimeDialogVisible" width="600">
      <el-form :model="changeTimeForm" label-width="120px">
        <el-form-item label="期望服务时间">
          <el-date-picker
            v-model="changeTimeForm.expectedTime"
            type="datetime"
            placeholder="期望服务时间"
            value-format="YYYY-MM-DD HH:mm:ss" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="changeTimeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleChangeTimeSubmit">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Task">
import { listTask, updateTask, getTask } from "@/api/service/task";
import ImageUpload from "@/components/ImageUpload";

const { proxy } = getCurrentInstance();
const { sys_task_type } = proxy.useDict("sys_task_type");

//表格任务列表集合
const taskList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
//控制显示隐藏取消编辑框
const cancelDialogVisible = ref(false);
//控制显示隐藏执行编辑框
const executeDialogVisible = ref(false);
//查看任务详情对话框
const viewDialogVisible = ref(false);
//改期任务的对话框
const changeTimeDialogVisible = ref(false);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    //这里status=1 待执行  2已执行 3已取消
    //页面初始化时默认查询待执行的任务
    //当用户切换taps栏时，根据status的值去已执行 或者其他的任务
    status: 1,
    oldName: null,
    nurseName: null,
    nursingProject: null,
    expectedTime: null,
  },
  cancelForm: {
    id: null,
    cancelReason: "",
  },
  executeForm: {
    id: null,
    executionTime: null,
    executionImages: "",
    executionRecord: null,
  },
  executeRules: {
    executionTime: [
      { required: true, message: "请选择执行时间", trigger: "change" },
    ],
    executionImages: [
      { required: true, message: "请上传执行图片", trigger: "change" },
    ],
    executionRecord: [
      { required: true, message: "请填写执行记录", trigger: "blur" },
    ],
  },
  viewForm: {},
  //改期任务的表单数据
  changeTimeForm: {
    id: null,
    expectedTime: null,
  },
});

const {
  queryParams,
  form,
  cancelForm,
  executeForm,
  executeRules,
  viewForm,
  changeTimeForm,
} = toRefs(data);

/** 查询护理任务列表 */
function getList() {
  loading.value = true;
  listTask(queryParams.value).then((response) => {
    taskList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    caregiverId: null,
    projectId: null,
    elderId: null,
    bedNo: null,
    taskType: null,
    expectedTime: null,
    executionRecord: null,
    cancelReason: null,
    status: null,
    relatedDocNo: null,
    executionImages: null,
    createdAt: null,
    updatedAt: null,
    createdBy: null,
    updatedBy: null,
    remark: null,
    extend1: null,
    extend2: null,
  };
  proxy.resetForm("taskRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 点击状态栏按钮时触发状态切换操作 */
function handleStatusChange(status) {
  queryParams.value.status = status;
  queryParams.value.pageNum = 1; // 重置到第一页
  getList();
}

/**点击取消 取消任务执行 
  还需要存储取消原因
*/
function handleCancel(row) {
  cancelForm.value.id = row.id;
  cancelForm.value.cancelReason = "";
  cancelDialogVisible.value = true;
}

/** 确认取消任务 */
function handleCancelSubmit() {
  if (!cancelForm.value.cancelReason.trim()) {
    proxy.$modal.msgError("请填写取消原因");
    return;
  }

  const params = {
    id: cancelForm.value.id,
    status: 3,
    cancelReason: cancelForm.value.cancelReason,
  };

  updateTask(params).then(() => {
    proxy.$modal.msgSuccess("取消成功");
    cancelDialogVisible.value = false;
    getList();
  });
}

/**点击执行按钮 */
function handleExecute(row) {
  executeForm.value.id = row.id;
  // 自动填充当前时间
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const day = String(now.getDate()).padStart(2, "0");
  const hours = String(now.getHours()).padStart(2, "0");
  const minutes = String(now.getMinutes()).padStart(2, "0");
  const seconds = String(now.getSeconds()).padStart(2, "0");
  executeForm.value.executionTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  executeForm.value.executionImages = "";
  executeForm.value.executionRecord = null;
  executeDialogVisible.value = true;
}

/**处理执行任务 */
function handleExecuteSubmit() {
  proxy.$refs.executeFormRef.validate((valid) => {
    if (valid) {
      // 处理 executionImages 字段，将数组格式字符串转换为普通字符串
      let processedExecutionImages = executeForm.value.executionImages;

      // 如果是数组格式的字符串，提取第一个元素
      if (
        typeof processedExecutionImages === "string" &&
        processedExecutionImages.startsWith("[") &&
        processedExecutionImages.endsWith("]")
      ) {
        try {
          const imageArray = JSON.parse(processedExecutionImages);
          if (Array.isArray(imageArray) && imageArray.length > 0) {
            processedExecutionImages = imageArray[0]; // 取第一个图片路径
          }
        } catch (e) {
          console.warn("解析 executionImages 失败:", e);
        }
      }

      const params = {
        id: executeForm.value.id,
        status: 2,
        executionImages: processedExecutionImages,
        executionRecord: executeForm.value.executionRecord,
        expectedTime: executeForm.value.executionTime,
      };

      updateTask(params).then(() => {
        proxy.$modal.msgSuccess("执行成功");
        executeDialogVisible.value = false;
        getList();
      });
    }
  });
}

/**查看任务详情 */
function handleView(row) {
  getTask(row.id).then((response) => {
    viewForm.value = response.data;
    // 处理执行图片
    if (viewForm.value.executionImages) {
      let images = viewForm.value.executionImages;

      // 如果是数组格式的字符串，解析为数组
      if (
        typeof images === "string" &&
        images.startsWith("[") &&
        images.endsWith("]")
      ) {
        try {
          const imageArray = JSON.parse(images);
          if (Array.isArray(imageArray)) {
            viewForm.value.parsedExecutionImages = imageArray;
          } else {
            viewForm.value.parsedExecutionImages = [images];
          }
        } catch (e) {
          // 解析失败，当作普通字符串处理
          viewForm.value.parsedExecutionImages = [images];
        }
      } else {
        // 普通字符串，转换为数组格式以便统一显示
        viewForm.value.parsedExecutionImages = [images];
      }
    } else {
      viewForm.value.parsedExecutionImages = [];
    }
    viewDialogVisible.value = true;
  });
}

/**点击改期按钮 打开对话框 */
function handleChangeTime(row) {
  changeTimeForm.value.id = row.id;
  changeTimeForm.value.expectedTime = "";
  changeTimeDialogVisible.value = true;
}

/** 确认改期任务 */
function handleChangeTimeSubmit() {
  if (!changeTimeForm.value.expectedTime) {
    proxy.$modal.msgError("请选择期望服务时间");
    return;
  }

  const params = {
    id: changeTimeForm.value.id,
    expectedTime: changeTimeForm.value.expectedTime,
  };

  updateTask(params).then(() => {
    proxy.$modal.msgSuccess("改期成功");
    changeTimeDialogVisible.value = false;
    getList();
  });
}

/** 格式化护理员姓名列表 */
function formatNurseNameList(nurseNameList) {
  // 处理空值或null的情况
  if (
    !nurseNameList ||
    !Array.isArray(nurseNameList) ||
    nurseNameList.length === 0
  ) {
    return "-";
  }

  // 过滤掉空字符串和null值，然后用逗号连接
  return nurseNameList.filter((name) => name && name.trim()).join(",");
}

getList();
</script>
